<?php

namespace SC\Qiniu;

use Qiniu;


class QiniuClient
{
    protected $uploadToken = null;
    protected $uploadManager = null;
    protected $bucketManager = null;

    function __construct()
    {
        $this->ak = config('qiniu.access_key');
        $this->sk = config('qiniu.secret_key');
        $this->bucket = config('qiniu.bucket');
        $this->host = config('qiniu.host');

        $this->auth = new Qiniu\Auth($this->ak, $this->sk);
    }

    function getUploadToken()
    {
        if (is_null($this->uploadToken)) {
            $this->uploadToken = $this->auth->uploadToken($this->bucket);
        }
        return $this->uploadToken;
    }

    function getUploadManager()
    {
        if (is_null($this->uploadManager)) {
            $this->uploadManager = new Qiniu\Storage\UploadManager();
        }

        return $this->uploadManager;
    }

    function getBucketManager()
    {
        if (\is_null($this->bucketManager)) {
            $this->bucketManager = new \Qiniu\Storage\BucketManager($this->auth, new \Qiniu\Config());
        }

        return $this->bucketManager;
    }

    /**
     * @Return ($url, $err)
     */
    function uploadData($key, $data)
    {
        list($ret, $err) = $this->getUploadManager()->put($this->getUploadToken(), $key, $data);
        return [
            rtrim($this->host, '/') . '/' . $key,
            $err,
        ];
    }

    /**
     * @Return $err
     */
    function remove($key)
    {
        return $this->getBucketManager()->delete($this->bucket, $key);
    }
}